# -*- coding: utf-8 -*-
import os
import glob
import maya.cmds as mc
import custom
reload(custom)
from liberHook.BaseHook import BaseHook
from liberLibs.dccLibs import Maya
from liberLibs.dccLibs import Assembly


class Hook(BaseHook):
    def __init__(self, library, directory, ext, start, end):
        BaseHook.__init__(self, library, directory, ext, start, end)

    def file_path(self, folder_name, ext):
        file_ = os.path.join(self.directory, folder_name, "%s%s" % (self.name, ext)).replace("\\", "/")
        return file_

    def execute(self):
        # new file
        Maya.new_file()
        ad_file = os.path.join(self.location, "%s.ma" % self.name).replace("\\", "/")
        folders = custom.assembly_unit
        reps = list()
        for folder in folders:
            folder_path = os.path.join(self.directory, folder).replace("\\", "/")
            if not os.path.isdir(folder_path):
                continue
            if folder == "gpu":
                file_ = self.file_path(folder, ".abc")
                if os.path.isfile(file_):
                    reps.append(["Cache", "cache", file_])
            elif folder == "rs":
                rs_files = glob.glob("%s/*.rs" % folder_path)
                if rs_files:
                    file_ = self.file_path(folder, ".ma")
                    Maya.new_file()
                    Maya.create_rs_proxy(rs_files)
                    Maya.save_as(file_)
                    reps.append(["Scene", "rs_proxy", file_])
            elif folder == "ass":
                ass_files = glob.glob("%s/*.ass" % folder_path)
                if ass_files:
                    file_ = self.file_path(folder, ".ma")
                    Maya.new_file()
                    Maya.create_ass_proxy(ass_files)
                    Maya.save_as(file_)
                    reps.append(["Scene", "ar_proxy", file_])
            elif folder == "mb":
                file_ = self.file_path(folder, ".mb")
                if os.path.isfile(file_):
                    reps.append(["Scene", "mb", file_])
            elif folder == "ma":
                file_ = self.file_path(folder, ".ma")
                if os.path.isfile(file_):
                    reps.append(["Scene", "ma", file_])
        if not reps:
            return
        Maya.new_file()
        for each in reps:
            rep_type, rep, path = each
            self.create_ad(rep_type, rep, path)
        Maya.save_as(ad_file)
        assembly = Assembly.Assembly()
        node_name = "%s_AD" % self.name
        assembly.set_active(node_name, "cache")

    def create_ad(self, rep_type, rep, path):
        assembly = Assembly.Assembly()
        node_name = "%s_AD" % self.name
        if not mc.objExists(node_name):
            assembly.create_assembly_node(node_name, "assemblyDefinition")
        if os.path.isfile(path):
            assembly.create_representation(node_name, rep_type, rep, rep, path)
